package top.wardyan.base.config;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * 程序设定. 读取自AppConfig.txt
 * @author ward
 *
 * 2019年2月16日
 */
public class AppConfig2 {
	
	private static final String FILENAME = "AppConfig.txt";
	protected static final Logger log = Logger.getLogger(AppConfig2.class);
	protected static final Map<String, String> configs = new HashMap<>();
	protected static AppConfig2 instance = null;
	
	protected AppConfig2(){
		try(BufferedReader reader = new BufferedReader(new FileReader(Path.of(FILENAME).toAbsolutePath().toString()))){
			String line = reader.readLine();
			while(line != null) {
				line = line.trim();
				String name = getName(line);
				String value = getValue(line);
				if(line.length() > 0 && !line.startsWith("#") && name != null && value != null) {
					configs.put(name.trim(), value.trim());
				}
				line = reader.readLine();
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error(e);
			System.exit(-999);
		}
	}
	
	public static AppConfig2 getInstance(){	// synchronized
		if(instance == null) 
			instance = new AppConfig2();
		
		return instance;
	}
	
	
	protected static String getName(String line) {
		return line != null && line.indexOf("=") > 0 ? line.substring(0, line.indexOf("=")) : "";
	}
	
	protected static String getValue(String line) {
		return line != null && line.indexOf("=") > 0 ? line.substring(line.indexOf("=") + 1) : "";
	}
	
	public static String get(String key) {
		return configs.get(key);
	}
	
	
	public static void main(String[] args) {
		/**
		AppConfig c = new AppConfig();
		c.configs.forEach((k, v) ->{
			System.out.println("V:" + get(k));
		});
		**/
		//AppConfig c = new AppConfig();
		System.out.println(AppConfig2.get("dbName"));
	}
	
}
